package com.salt.modules.sys.service;

import com.google.common.collect.Lists;
import com.salt.common.json.AjaxJson;
import com.salt.common.utils.Merge;
import com.salt.common.utils.StringUtils;
import com.salt.core.sms.SmsTemplate;
import com.salt.core.sms.model.SmsCode;
import com.salt.modules.sys.entity.Role;
import com.salt.modules.sys.entity.User;
import com.salt.modules.sys.entity.UserRegisterParam;
import com.salt.modules.sys.mapper.RoleMapper;
import com.salt.modules.sys.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description 用户注册业务类
 * @Author salt
 * @Date 2022/9/8
 * @Version 1.0.1
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class UserRegisterService {

    private final UserService userService;
    private final SmsTemplate smsTemplate;
    private final RoleMapper roleMapper;
    private final UserMapper userMapper;

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public AjaxJson register(UserRegisterParam userRegisterParam){
        // 申请注册
        if (StringUtils.isBlank(userRegisterParam.getMobile())) {
            return AjaxJson.error("手机号不能为空!");
        }

        if (StringUtils.isBlank(userRegisterParam.getPassword())) {
            return AjaxJson.error("密码不能为空!");
        }

        if (StringUtils.isBlank(userRegisterParam.getLoginName())) {
            return AjaxJson.error("账号不能为空!");
        }


        // 账号是否已经注册
        if (userMapper.countByLoginName(userRegisterParam.getLoginName()) > 0) {
            return AjaxJson.error("该账号已注册，无法重复注册!");
        }


        // 手机验证码是否正确
        String mobile = userRegisterParam.getMobile().replaceAll("\\s*", "");
        SmsCode smsCode = new SmsCode()
                .setId(userRegisterParam.getValidate() + mobile)
                .setValue(userRegisterParam.getSmsCode());
        if (!smsTemplate.validateMessage(smsCode)) {
            return AjaxJson.error("手机验证码有误");
        }


        // 注册
        User user = new User();
        if (StringUtils.isNotBlank(userRegisterParam.getRealName())) {
            user.setName(userRegisterParam.getRealName());
        } else {
            user.setName(Merge.string("盐云_", mobile));
        }
        user.setMobile(mobile);
        user.setPassword(userService.entryptPassword(userRegisterParam.getPassword()));
        // 设置账号即登录名
        if (StringUtils.isNotBlank(userRegisterParam.getLoginName())) {
            user.setLoginName(userRegisterParam.getLoginName());
        } else {
            user.setLoginName(mobile);
        }
        List<Role> roleList = Lists.newArrayList(); // 注册后默认拥有的角色
        roleList.add(roleMapper.get("0"));
        user.setRoleList(roleList);
        userService.saveUser(user);
        return AjaxJson.success("注册成功!");
    }
}
